package com.gitee.wsl.doc.prosemirror.state.ext

import com.gitee.wsl.doc.prosemirror.model.content.ResolvedPos
import com.gitee.wsl.doc.prosemirror.model.fragment.Slice
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.TextSelection
import com.gitee.wsl.doc.prosemirror.transform.ext.replaceStep
import com.gitee.wsl.doc.prosemirror.transform.ext.step
import com.gitee.wsl.doc.prosemirror.transform.step.ReplaceStep


/**
 * 合并两个相邻文本块的辅助函数。
 * @param state 编辑器状态对象
 * @param cut 分割位置对象
 * @param dispatch 事务处理回调函数（可选）
 * @return 操作是否成功执行
 */
fun EditorState.joinTextblocksAround(
    cut: ResolvedPos,
    dispatch: CommandDispatch? = null
): Boolean {
    val state = this
    val before = cut.nodeBefore!!
    var beforeText = before
    var beforePos = cut.pos - 1

    // 遍历找到最近的文本块
    while (!beforeText.isTextblock) {
        if (beforeText.type.spec.isolating == true) return false
        val child = beforeText.lastChild
        if (child == null) return false
        beforeText = child
        beforePos--
    }

    val after = cut.nodeAfter!!
    var afterText = after
    var afterPos = cut.pos + 1

    // 遍历找到最近的文本块
    while (!afterText.isTextblock) {
        if (afterText.type.spec.isolating == true) return false
        val child = afterText.firstChild
        if (child == null) return false
        afterText = child
        afterPos++
    }

    // 创建替换步骤
    val step = state.doc.replaceStep( beforePos, afterPos, Slice.empty)
    if (step == null || step.from != beforePos || (step is ReplaceStep && step.slice.size >= afterPos - beforePos)) {
        return false
    }

    if (dispatch != null) {
        val tr = state.tr.step(step)
        tr.setSelection(TextSelection.create(tr.doc, beforePos))
        dispatch(tr.scrollIntoView())
    }

    return true
}